package com.whq.knowverywell.util;

/**
 * 十六进制工具类
 * @author wanghuaiqiang
 *
 */
public class HexUtil {

	/**
	 * Convert byte to hex string.
	 * 
	 * @param byte0
	 *            byte value.
	 * @return hex string of byte.
	 */
	public static final String hexString(byte byte0) {// 字节到十六进制的ASCII码转换
		char ac[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		char ac1[] = new char[2];
		ac1[0] = ac[byte0 >>> 4 & 0xf];
		ac1[1] = ac[byte0 & 0xf];
		String s = new String(ac1);
		return s;
	}

	/**
	 * Convert byte array to hex string.
	 * 
	 * @param bytes
	 *            - byte array.
	 * @return hex string.
	 */
	public static final String hexString(byte[] bytes) {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			buffer.append(hexString(bytes[i]));
		}

		return buffer.toString();
	}

	/**
	 * @param b
	 *            source byte array.
	 * @param offset
	 *            starting offset.
	 * @param len
	 *            number of bytes in destination (processes len*2).
	 * @return byte[len].
	 */
	public static byte[] hex2byte(byte[] b, int offset, int len) {
		byte[] d = new byte[len];
		for (int i = 0; i < len * 2; i++) {
			int shift = i % 2 == 1 ? 0 : 4;
			d[i >> 1] |= Character.digit((char) b[offset + i], 16) << shift;
		}
		return d;
	}

	/**
	 * @param s
	 *            source string (with Hex representation)
	 * @return byte array
	 */
	public static byte[] hex2byte(String s) {
		if (s.length() % 2 == 0) {
			return hex2byte(s.getBytes(), 0, s.length() >> 1);
		} else {
			throw new RuntimeException("Uneven number(" + s.length()
					+ ") of hex digits passed to hex2byte.");
		}
	}

}
